package com.one.blocks.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.blocks.common.exception.JsonException;
import lombok.experimental.UtilityClass;

import java.io.IOException;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-10-18 11:10:26
 */
@UtilityClass
public class JsonUtil {

    public static ObjectMapper GLOBAL_OBJECT_MAPPER;

    public static void inject(ObjectMapper objectMapper) {
        GLOBAL_OBJECT_MAPPER = objectMapper;
    }

    public static String toString(Object o) {
        try {
            return GLOBAL_OBJECT_MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new JsonException(e);
        }
    }

    public static byte[] toBytes(Object o) {
        try {
            return GLOBAL_OBJECT_MAPPER.writeValueAsBytes(o);
        } catch (JsonProcessingException e) {
            throw new JsonException(e);
        }
    }

    public static <T> T parse(String value, Class<T> typeReference) {
        try {
            return GLOBAL_OBJECT_MAPPER.readValue(value, typeReference);
        } catch (JsonProcessingException e) {
            throw new JsonException(e);
        }
    }

    public static <T> T parse(String value, TypeReference<T> typeReference) {
        try {
            return GLOBAL_OBJECT_MAPPER.readValue(value, typeReference);
        } catch (JsonProcessingException e) {
            throw new JsonException(e);
        }
    }

    public static <T> T parse(byte[] value, Class<T> typeReference) {
        try {
            return GLOBAL_OBJECT_MAPPER.readValue(value, typeReference);
        } catch (IOException e) {
            throw new JsonException(e);
        }
    }

    public static <T> T parse(byte[] value, TypeReference<T> typeReference) {
        try {
            return GLOBAL_OBJECT_MAPPER.readValue(value, typeReference);
        } catch (IOException e) {
            throw new JsonException(e);
        }
    }
}
